package web.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class LoginServelt extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取用户名和密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        //判断是否要记住用户名
        String remember = req.getParameter("remember");

        Cookie cookie = new Cookie("username",username);
        Cookie statusCookie = new Cookie("rememberStatus","true");
        if ("true".equals(remember)){
            //要记住用户名
            cookie.setMaxAge(60*60*24*7); //7天
            statusCookie.setMaxAge(60*60*24*7); //7天
        }else{
            //取消记住用户名
            cookie.setMaxAge(0);
            statusCookie.setMaxAge(0);
        }

        cookie.setPath(req.getContextPath());
        statusCookie.setPath(req.getContextPath());

        resp.addCookie(cookie);
        resp.addCookie(statusCookie);

        //登录逻辑

        //重定向回到登录页面
        resp.sendRedirect(req.getContextPath() + "/login.jsp");
    }

}
